"use client"

import { useState } from "react"
import { ChevronDown, ChevronRight, File, Folder, FolderOpen, Copy } from "lucide-react"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Badge } from "@/components/ui/badge"
import { useToast } from "@/hooks/use-toast"
import type { DirectoryNode, FileNode } from "@/lib/langgraph-generator-v2"

interface FileTreeViewerProps {
  directory: DirectoryNode
  defaultExpanded?: boolean
}

export function FileTreeViewer({ directory, defaultExpanded = true }: FileTreeViewerProps) {
  const [expandedDirs, setExpandedDirs] = useState<Set<string>>(
    defaultExpanded ? new Set([directory.path]) : new Set()
  )
  const [selectedFile, setSelectedFile] = useState<FileNode | null>(null)
  const { toast } = useToast()

  const toggleDirectory = (path: string) => {
    const newExpanded = new Set(expandedDirs)
    if (newExpanded.has(path)) {
      newExpanded.delete(path)
    } else {
      newExpanded.add(path)
    }
    setExpandedDirs(newExpanded)
  }

  const copyFileContent = async (file: FileNode) => {
    try {
      await navigator.clipboard.writeText(file.content)
      toast({
        title: "复制成功",
        description: `${file.name} 的内容已复制到剪贴板`,
      })
    } catch (err) {
      toast({
        title: "复制失败",
        description: "请手动复制代码",
        variant: "destructive",
      })
    }
  }

  return (
    <div className="flex gap-4 h-full overflow-hidden">
      {/* 左侧文件树 */}
      <div className="w-80 border-r flex flex-col h-full">
        <div className="p-3 border-b bg-muted/30 shrink-0">
          <h3 className="font-semibold text-sm flex items-center gap-2">
            <Folder className="h-4 w-4" />
            目录结构
          </h3>
        </div>
        <div className="flex-1 overflow-hidden">
          <div className="h-full overflow-y-auto overflow-x-hidden custom-scrollbar smooth-scroll">
            <div className="p-2">
              <DirectoryTree
                directory={directory}
                expandedDirs={expandedDirs}
                selectedFile={selectedFile}
                onToggleDirectory={toggleDirectory}
                onSelectFile={setSelectedFile}
                level={0}
              />
            </div>
          </div>
        </div>
      </div>

      {/* 右侧代码查看器 */}
      <div className="flex-1 flex flex-col min-w-0 h-full overflow-hidden">
        {selectedFile ? (
          <>
            <div className="p-3 border-b bg-muted/30 flex items-center justify-between shrink-0">
              <div className="flex items-center gap-2 min-w-0">
                <File className="h-4 w-4 shrink-0" />
                <span className="font-medium text-sm truncate">{selectedFile.name}</span>
                <Badge variant="outline" className="shrink-0 text-xs">
                  {selectedFile.language}
                </Badge>
              </div>
              <Button variant="ghost" size="sm" onClick={() => copyFileContent(selectedFile)}>
                <Copy className="mr-2 h-4 w-4" />
                复制
              </Button>
            </div>
            <div className="flex-1 overflow-hidden">
              <div className="h-full overflow-y-auto overflow-x-hidden custom-scrollbar smooth-scroll">
                <pre className="p-4 text-xs font-mono whitespace-pre-wrap break-words leading-relaxed">
                  <code className={`language-${selectedFile.language}`}>{selectedFile.content}</code>
                </pre>
              </div>
            </div>
          </>
        ) : (
          <div className="flex items-center justify-center h-full text-muted-foreground">
            <div className="text-center space-y-2">
              <File className="h-12 w-12 mx-auto opacity-50" />
              <p className="text-sm">选择一个文件查看内容</p>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

interface DirectoryTreeProps {
  directory: DirectoryNode
  expandedDirs: Set<string>
  selectedFile: FileNode | null
  onToggleDirectory: (path: string) => void
  onSelectFile: (file: FileNode) => void
  level: number
}

function DirectoryTree({
  directory,
  expandedDirs,
  selectedFile,
  onToggleDirectory,
  onSelectFile,
  level,
}: DirectoryTreeProps) {
  const isExpanded = expandedDirs.has(directory.path)
  const indent = level * 16

  return (
    <div>
      {/* 目录名 */}
      <button
        onClick={() => onToggleDirectory(directory.path)}
        className="flex items-center gap-2 w-full text-left py-1 px-2 rounded hover:bg-accent transition-colors"
        style={{ paddingLeft: `${indent + 8}px` }}
      >
        {isExpanded ? (
          <ChevronDown className="h-4 w-4 shrink-0" />
        ) : (
          <ChevronRight className="h-4 w-4 shrink-0" />
        )}
        {isExpanded ? (
          <FolderOpen className="h-4 w-4 shrink-0 text-blue-500" />
        ) : (
          <Folder className="h-4 w-4 shrink-0 text-blue-500" />
        )}
        <span className="text-sm font-medium">{directory.name}</span>
        <Badge variant="secondary" className="ml-auto text-xs">
          {directory.files.length + directory.subdirectories.length}
        </Badge>
      </button>

      {/* 展开的内容 */}
      {isExpanded && (
        <div>
          {/* 文件列表 */}
          {directory.files.map((file) => (
            <button
              key={file.path}
              onClick={() => onSelectFile(file)}
              className={`flex items-center gap-2 w-full text-left py-1 px-2 rounded transition-colors ${
                selectedFile?.path === file.path ? "bg-accent" : "hover:bg-accent/50"
              }`}
              style={{ paddingLeft: `${indent + 40}px` }}
            >
              <File className="h-4 w-4 shrink-0 text-gray-500" />
              <span className="text-sm">{file.name}</span>
              <Badge variant="outline" className="ml-auto text-xs">
                {file.language}
              </Badge>
            </button>
          ))}

          {/* 子目录 */}
          {directory.subdirectories.map((subdir) => (
            <DirectoryTree
              key={subdir.path}
              directory={subdir}
              expandedDirs={expandedDirs}
              selectedFile={selectedFile}
              onToggleDirectory={onToggleDirectory}
              onSelectFile={onSelectFile}
              level={level + 1}
            />
          ))}
        </div>
      )}
    </div>
  )
}
